package com.xiaoran.service.connector.handler;

import com.xiaoran.common.data.RpcRequest;
import com.xiaoran.common.utils.JsonSerializerUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcServerDecodeHandler extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext,
                          ByteBuf in,
                          List<Object> list) throws Exception {
        
        if (in.readableBytes()<=4){
            return;
        }
        //表头，规定内容有多长，可以有效的防止粘包
        int length = in.readInt();
        in.markReaderIndex(); //标记已读
        if (in.readableBytes()<length){
            in.resetReaderIndex(); //重置阅读索引
        }else {
            byte[] bytes = new byte[in.readableBytes()];
            in.readBytes(bytes);
            RpcRequest znsRequest = JsonSerializerUtil.deserialize(bytes, RpcRequest.class);
            list.add(znsRequest);
        }
        
    }
}
